package com.sphd.beautysalon.activitys.recorder;

import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v4.app.ActivityCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import com.gprinter.aidl.GpService;
import com.gprinter.command.EscCommand;
import com.gprinter.command.GpCom;
import com.sphd.beautysalon.info.LoginInfo;
import com.sphd.beautysalon.presenter.OrdersInfoPresenterImpl;
import com.sphd.beautysalon.view.OrdersInfoView;
import com.sphd.beautysalon.R;
import com.sphd.beautysalon.adapters.OrderParticalarsAdapter;
import com.sphd.beautysalon.base.BaseActivity;
import com.sphd.beautysalon.base.RestaurantUrl;
import com.sphd.beautysalon.info.FoodInfo;
import com.sphd.beautysalon.info.RestaurantInfo;
import com.sphd.beautysalon.info.SalesInfo;
import com.sphd.beautysalon.utils.Constant;
import com.wzh.frame.utils.StringUtils;

import org.apache.commons.lang.ArrayUtils;
import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 订单详情展示页面
 */
public class OrdersInfoActivity extends BaseActivity implements OrdersInfoView {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.user_message)
    TextView userMessage;
    @BindView(R.id.state_textview)
    TextView stateTextview;
    @BindView(R.id.receive_btn)
    Button receiveBtn;
    @BindView(R.id.cancel_btn)
    Button cancelBtn;
    @BindView(R.id.my_recy)
    RecyclerView myRecy;
    @BindView(R.id.my_swf)
    SwipeRefreshLayout mySwf;
    @BindView(R.id.content_orders_info)
    LinearLayout contentOrdersInfo;
    Intent intent;
    Bundle bundle;
    SalesInfo salesInfo;
    OrdersInfoPresenterImpl ordersInfoPresenter;
    TextView sphjTextview;
    TextView yhqzkTextview;
    TextView yfjeTextview;
    TextView cardPayTextview;
    TextView xjzfTextview;
    TextView cardmoneyTextview;

    TextView addressTextview;
    TextView usernameTextview;
    TextView userPhoneTextview;
    LinearLayout orderAddressLinear;
    @BindView(R.id.write_bill)
    Button writeBill;
    private View footView;
    private OrderParticalarsAdapter orderParticalarsAdapter;
    private LoginInfo loginInfo;
    private RestaurantInfo restaurantInfo;
    private GpService mGpService;
    private PrinterServiceConnection conn = null;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_orders_info);
        ButterKnife.bind(this);
        initView();
        initEvent();
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    private void initEvent() {
        toolbar.setNavigationOnClickListener(view -> {
            setResult(0);
            finish();
        });
    }

    private void initView() {
        setTitleBar(toolbar, "订单详情");
        intent = getIntent();
        bundle = intent.getExtras();
        salesInfo = (SalesInfo) bundle.getSerializable(Constant.SALESINFO);
        restaurantInfo = (RestaurantInfo) bundle.getSerializable(Constant.RESTAURANTSINFO);
        loginInfo = DataSupport.findLast(LoginInfo.class);
        userMessage.setText(salesInfo.getOrder_username() + "\n" + salesInfo.getOrder_memphone());
        ordersInfoPresenter = new OrdersInfoPresenterImpl(this);
        connection();
        initState();
        initFootWiew();
        initAdapter();
        addData();
    }

    private void initFootWiew() {
        footView = View.inflate(context, R.layout.order_particulars_foot, null);
        sphjTextview = $(R.id.sphj_textview, footView);
        yhqzkTextview = $(R.id.yhqzk_textview, footView);
        yfjeTextview = $(R.id.yfje_textview, footView);

        cardPayTextview = $(R.id.card_pay_textview, footView);
        xjzfTextview = $(R.id.xjzf_textview, footView);

        cardmoneyTextview = $(R.id.cardmoney_textview, footView);

        orderAddressLinear = $(R.id.order_address_linear, footView);

        addressTextview = $(R.id.address_textview, footView);
        usernameTextview = $(R.id.username_textview, footView);
        userPhoneTextview = $(R.id.user_phone_textview, footView);

        sphjTextview.setText("￥" + (turn(salesInfo.getOrder_ticket() +
                salesInfo.getOrder_lastprice() + salesInfo.getOrder_cardpay(),Constant.DECIMAL_POINT)));
        yhqzkTextview.setText("￥" + turn(salesInfo.getOrder_ticket(),Constant.DECIMAL_POINT));
        yfjeTextview.setText("￥" + (turn((salesInfo.getOrder_lastprice() + salesInfo.getOrder_cardpay()),Constant.DECIMAL_POINT)));
        cardPayTextview.setText("￥" + turn(salesInfo.getOrder_cardpay(),Constant.DECIMAL_POINT));
        xjzfTextview.setText("￥" + turn(salesInfo.getOrder_lastprice(),Constant.DECIMAL_POINT));
        addressTextview.setText("" + salesInfo.getOrder_addr());
        usernameTextview.setText("" + salesInfo.getOrder_recName());
        userPhoneTextview.setText("" + salesInfo.getOrder_uphone());
        cardmoneyTextview.setText("￥"+turn(salesInfo.getMem_account()));
        if (salesInfo.getOrder_isosale() == 1) {
            orderAddressLinear.setVisibility(View.VISIBLE);
        } else {
            orderAddressLinear.setVisibility(View.GONE);
        }
    }


    private void initAdapter() {
        setRecy(myRecy);
        setRefresh(mySwf);
        orderParticalarsAdapter = new OrderParticalarsAdapter(R.layout.item_order_particulars, new ArrayList<>(), salesInfo, this);
        myRecy.setAdapter(orderParticalarsAdapter);
        orderParticalarsAdapter.addFooterView(footView);

    }

    private void addData() {
        ordersInfoPresenter.addData(RestaurantUrl.Httptitle + RestaurantUrl.ORDER_GET_FOOD + "orderno=" + salesInfo.getOrder_no());
    }

    private void initState() {
        switch (salesInfo.getOrder_status()) {
            case 0:
                stateTextview.setText("未接收");
                receiveBtn.setText("接收");
                break;
            case 1:
                cancelBtn.setVisibility(View.GONE);

                stateTextview.setText("已接受");
                if (salesInfo.getOrder_isosale() == 1) {
                    receiveBtn.setText("派送");
                } else {
                    receiveBtn.setText("结账");
                }

                break;
            case 2:
                cancelBtn.setVisibility(View.GONE);
                stateTextview.setText("派送中");
                receiveBtn.setText("结账");
                break;
            case 3:
                stateTextview.setText("已完成");
                cancelBtn.setVisibility(View.GONE);
                receiveBtn.setText("打印小票");
                break;
            case 4:
                cancelBtn.setVisibility(View.GONE);
                receiveBtn.setVisibility(View.GONE);
                break;
            case 6:
                cancelBtn.setVisibility(View.GONE);
                receiveBtn.setVisibility(View.GONE);
                break;
            default:
                break;
        }
    }

    @OnClick({R.id.receive_btn, R.id.cancel_btn, R.id.user_message,R.id.write_bill})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.receive_btn:
                if (isReciverCanDo(loginInfo, restaurantInfo)) {
                    if (receiveBtn.getText().equals("打印小票")){
                        printerOrder(salesInfo);


                    }else {
                    recOk(salesInfo);
                    }
                } else {
                    toast("暂无权限。");
                }
                break;
            case R.id.cancel_btn:
                if (isReciverCanDo(loginInfo, restaurantInfo)) {
                    showCancelDialog(salesInfo);
                } else {
                    toast("暂无权限。");
                }
                break;
            case R.id.write_bill:
                printerOrder(salesInfo);
                break;
            case R.id.user_message:


                AlertDialog.Builder alertdialogcall = new AlertDialog.Builder(context);
                alertdialogcall.setIcon(R.mipmap.phone).setTitle("拨打电话").
                        setMessage("确定要给" + salesInfo.getOrder_username() +
                                "\n" + salesInfo.getOrder_memphone() +
                                "打电话").setPositiveButton("确定",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                callPhone();

                            }
                        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                }).create().show();
                break;
        }
    }

    private void printerOrder(SalesInfo salesInfo) {
        EscCommand esc = new EscCommand();
        esc.addPrintAndFeedLines((byte) 3);
        esc.addSelectJustification(EscCommand.JUSTIFICATION.CENTER);//设置打印居中
        esc.addSelectPrintModes(EscCommand.FONT.FONTA, EscCommand.ENABLE.OFF, EscCommand.ENABLE.ON, EscCommand.ENABLE.ON, EscCommand.ENABLE.OFF);//设置为倍高倍宽
        esc.addText("订单详情");   //  打印文字
        esc.addPrintAndFeedLines((byte) 2);

        /*打印文字*/
        esc.addSelectPrintModes(EscCommand.FONT.FONTA, EscCommand.ENABLE.OFF, EscCommand.ENABLE.OFF, EscCommand.ENABLE.OFF, EscCommand.ENABLE.OFF);//取消倍高倍宽
        esc.addSelectJustification(EscCommand.JUSTIFICATION.LEFT);//设置打印左对齐

        esc.addSelectJustification(EscCommand.JUSTIFICATION.LEFT);//设置打印左对齐
        String s = "商品名\t";
        s = getStr(s);

        esc.addText(s);   //  打印文字RiCC
        esc.addText("商品数量\t");
        esc.addText("单价\n");
        List<FoodInfo> foodInfos=orderParticalarsAdapter.getData();
        for (int i = 0; i < foodInfos.size(); i++) {
//            esc.addPrintAndFeedLines((byte) 2);
            esc.addPrintAndLineFeed();
            String proname = foodInfos.get(i).getDetail_dname();
            proname = getStr(proname);
            esc.addText(proname);   //  打印文字RiCC
            esc.addHorTab();
            esc.addText("" + foodInfos.get(i).getDetail_dnumber());
            esc.addHorTab();
            esc.addText("￥" + foodInfos.get(i).getDetail_price());
            esc.addPrintAndLineFeed();
        }
        esc.addPrintAndFeedLines((byte) 2);
        esc.addSelectJustification(EscCommand.JUSTIFICATION.LEFT);//设置打印左对齐
        esc.addText("现金支付");   //  打印文字
        esc.addSelectJustification(EscCommand.JUSTIFICATION.RIGHT);//设置打印左对齐
        esc.addText("" + salesInfo.getOrder_lastprice());   //  打印文字
        esc.addText("支付卡支付" + salesInfo.getOrder_cardpay() + "\n");   //  打印文字
        esc.addText("优惠券抵扣" + salesInfo.getOrder_ticket() + "\n");   //  打印文字
        esc.addText("商品合计" + (salesInfo.getOrder_lastprice() + salesInfo.getOrder_cardpay() + salesInfo.getOrder_ticket()) + "\n");   //  打印文字
        esc.addPrintAndLineFeed();
        esc.addSelectJustification(EscCommand.JUSTIFICATION.CENTER);//设置打印居中
        esc.addText("谢谢惠顾!\r\n");   //  打印结束
//        esc.addText("一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十");   //  打印结束
        esc.addPrintAndFeedLines((byte) 5);
        esc.addPrintAndLineFeed();
        Vector<Byte> datas = esc.getCommand(); //发送数据
        Byte[] Bytes = datas.toArray(new Byte[datas.size()]);
        byte[] bytes = ArrayUtils.toPrimitive(Bytes);
        String str = Base64.encodeToString(bytes, Base64.DEFAULT);
        int rel;
        try {
            rel = mGpService.sendEscCommand(0, str);
            GpCom.ERROR_CODE r = GpCom.ERROR_CODE.values()[rel];
            if (r != GpCom.ERROR_CODE.SUCCESS) {
                Toast.makeText(getApplicationContext(), GpCom.getErrorText(r),
                        Toast.LENGTH_SHORT).show();
            }
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    class PrinterServiceConnection implements ServiceConnection {
        @Override
        public void onServiceDisconnected(ComponentName name) {

            mGpService = null;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mGpService = GpService.Stub.asInterface(service);
        }
    }
    private void connection() {
        conn = new PrinterServiceConnection();
        Intent intent = new Intent();
        intent.setAction("com.gprinter.aidl.GpPrintService");
        intent.setPackage(getPackageName());
        bindService(intent, conn, Context.BIND_AUTO_CREATE); // bindService
    }
    private String getStr(String str) {
        int len = str.length();
        if (len < 8) {
            for (int i = len; i < 10; i++) {
                str += " ";
            }
        }
        return str;
    }
    private void callPhone() {
        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + salesInfo.getOrder_memphone()));
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            toast("暂无电话许可授权，请授权后使用该功能。");
            return;
        }
        startActivity(intent);
    }

    /**
     * 取消订单的提示框
     *
     * @param
     */
    private void showCancelDialog(final SalesInfo salesInfo) {
        LayoutInflater li = LayoutInflater.from(context);
        View promptsView = li.inflate(R.layout.layout_edittextdialog, null);
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                context);

        // set prompts.xml to alertdialog builder
        alertDialogBuilder.setView(promptsView);
        alertDialogBuilder.setTitle("订单:" + salesInfo.getOrder_no()
                + "\n取消原因");
        final EditText userInput = (EditText) promptsView
                .findViewById(R.id.input);
        userInput.setHint("");
        alertDialogBuilder
                .setCancelable(false)
                .setPositiveButton("确定",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // get user input and set it to result
                                // edit text
                                cancelOrdersNet(userInput.getText().toString(), salesInfo);

                            }
                        })
                .setNegativeButton("取消",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
                            }
                        });

        // create alert dialog
        AlertDialog alertDialog = alertDialogBuilder.create();

        // show it
        alertDialog.show();

    }

    private void cancelOrdersNet(String cancerOrder, SalesInfo salesInfo) {
        ordersInfoPresenter.sendCancleUrl(RestaurantUrl.Httptitle +
                RestaurantUrl.CancelSalesAndOrders + "remark=" + StringUtils.utf8Encode(cancerOrder) + "&orderno=" + salesInfo.getOrder_no());
    }

    private void recOk(SalesInfo item) {
        if (isReciverCanDo(loginInfo, restaurantInfo)) {
            if (item.getOrder_status() < 3) {
                Map<String, String> map = new HashMap<String, String>();
                map.put("orderno", item.getOrder_no());
                map.put("cgid", String.valueOf(item.getOrder_cgid()));
                map.put("memPhone", item.getOrder_memphone());
                map.put("type", "" + item.getOrder_pay());
                map.put("realprice", String.valueOf(item.getOrder_lastprice() + item.getOrder_cardpay()));
                map.put("cgname", item.getOrder_cg());
                map.put("isgive", restaurantInfo.isCg_isgive() ? "1" : "0");
                map.put("ticket", String.valueOf(item.getOrder_ticket()));
                map.put("isyh", restaurantInfo.isCg_isyh() ? "1" : "0");
                if (!StringUtils.isEmpty(item.getOrder_memcard())) {
                    map.put("memcard", item.getOrder_memcard());
                }
                switch (item.getOrder_status()) {
                    case 0:
                        map.put("orderStatus", "1");
                        break;
                    case 1:
                        if (item.getOrder_isosale() == 1) {
                            map.put("orderStatus", "2");
                        } else {
                            map.put("orderStatus", "3");
                        }

                        break;
                    case 2:
                        map.put("orderStatus", "3");
                        break;
                    case 3:
                        break;

                    default:
                        break;
                }

                ordersInfoPresenter.recUrl(RestaurantUrl.Httptitle + RestaurantUrl.ChangeStatus, map);

            }
        } else {
            toast("没有接单权限");
        }
    }

    @Override
    public void recList(List<FoodInfo> foodInfos) {
        orderParticalarsAdapter.setNewData(foodInfos);
    }

    @Override
    public void recRes(int res) {
        if (res == 1) {
            int type = salesInfo.getOrder_status();
            if (type == 0) {
                salesInfo.setOrder_status(1);
            } else if (type == 1) {
                if (salesInfo.getOrder_isosale() == 1) {
                    salesInfo.setOrder_status(2);
                } else {
                    salesInfo.setOrder_status(3);
                }
            } else if (type == 2) {
                salesInfo.setOrder_status(3);
            }
            initState();
        } else {
            toast("提交失败，请重试！");
        }
    }

    @Override
    public void recCancleRes(int status) {
        if (status == 1) {
            setResult(0);
            finish();
        } else {
            toast("取消失败，请重试！");
        }
    }

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    public Action getIndexApiAction() {
        Thing object = new Thing.Builder()
                .setName("OrdersInfo Page") // TODO: Define a title for the content shown.
                // TODO: Make sure this auto-generated URL is correct.
                .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
                .build();
        return new Action.Builder(Action.TYPE_VIEW)
                .setObject(object)
                .setActionStatus(Action.STATUS_TYPE_COMPLETED)
                .build();
    }

    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        AppIndex.AppIndexApi.start(client, getIndexApiAction());
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        AppIndex.AppIndexApi.end(client, getIndexApiAction());
        client.disconnect();
    }

    @Override
    public void showLoading() {
        showLoadingDialog();
    }

    @Override
    public void dissLoading() {
        dissLoadingDialog();
    }
}
